<?php

namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use backend\models\LoginForm;

class UserController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['get'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if(Yii::$app->request->isAjax && Yii::$app->request->isPost){
            return $this->_ajaxLogin(Yii::$app->request->post());
        }
        $this->layout = 'main-no-frame';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        return $this->render('login');
    }

    private function _ajaxLogin($data)
    {
        $result = [
            'status'=>200,
            'msg'=>''
        ];
        if(!$data){
            $result['status'] = 500;
            $result['msg'] = '参数传递有误';
            return $result;
        }
        $model = new LoginForm();
        $model->load($data, '');
        if(!$model->login()){
            $result['status'] = 500;
            $result['msg'] = '登陆失败请重试';
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $result;
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect(Yii::$app->user->loginUrl);
    }
}
